package com.lzy.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzy.common.QueryPageParam;
import com.lzy.entity.Result;
import com.lzy.entity.Teacher;
import com.lzy.service.ITeacherService;
import com.lzy.vo.TeacherWithClassVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-04-29
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {

    //日志对象
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TeacherController.class);

    @Autowired
    private ITeacherService teacherService;

    @GetMapping("/list")
    public Result list() {
        log.info("获取所有老师列表");
        return Result.success(teacherService.list());
    }

    @PostMapping("/listPage")
    public Result listPage2(@RequestBody QueryPageParam query) {
        log.info("获取老师列表分页");
        return teacherService.listPage(query);
    }

    //检查教师编号唯一性
    @GetMapping("/checkTNum")
    public Result checkTNum(@RequestParam String tNum, @RequestParam(required = false) Integer id) {
        log.info("检查教师编号唯一性, 编号: {}, ID: {}", tNum, id);
        LambdaQueryWrapper<Teacher> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Teacher::getTNum, tNum);

        // 如果是编辑操作，排除当前教师ID
        if (id != null) {
            // 使用LambdaQueryWrapper的ne方法构建SQL条件：id != #{id}
            // 这会生成SQL片段：AND id <> #{id}
            // 其中Teacher::getId是方法引用，用于获取字段名，id是排除的当前记录ID
            lambdaQueryWrapper.ne(Teacher::getId, id);
        }
        
        Teacher one = teacherService.getOne(lambdaQueryWrapper);
        return one == null ? Result.success(false) : Result.success(true);
    }

    //新增教师
    @PostMapping("/create")
    public Result create(@RequestBody TeacherWithClassVO teacher) {
        log.info("新增教师：{}", teacher);
        return teacherService.addTeacher(teacher);
    }

    //修改教师
    @PostMapping("/update")
    public Result update(@RequestBody TeacherWithClassVO teacher) {
        log.info("修改教师：{}", teacher);
        return teacherService.updateTeacher(teacher) ? Result.success() : Result.fail();
    }

    //删除教师
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        log.info("删除教师：{}", id);
        return teacherService.removeById(id) ? Result.success() : Result.fail();
    }
}
